package com.zx.map.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zx.scp.utils.PropertyUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zx.map.service.SystemBarService;
import com.zx.map.service.domain.CreditRepayInfoDownloadDomain;
import com.zx.map.service.domain.SystemBarDomain;
import com.zx.map.service.domain.SystemBarDownloadDomain;
import com.zx.map.service.model.CreditRepayInfoModel;
import com.zx.map.service.model.SystemBarModel;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;
import com.zx.platform.utils.report.ReportUtil;
import com.zx.scp.utils.MatrixToImageWriter;

@Controller
@RequestMapping("/manage/systemBar")
public class SystemBarController {
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(SystemBarController.class);

	@Autowired
	private SystemBarService systemBarService;
	/**
	 * 进入列表页面
	 *
	 */
	@RequestMapping("/productBar")
	public String productBar(SystemBarDomain domain, Model model,
			HttpServletRequest request) {

		try {// 初始化信息
			MatrixToImageWriter.realPath = request.getSession().getServletContext().getRealPath("/");
			
			Integer pageNum = domain.getPageNum();
			Integer pageSize = domain.getPageSize();
			Integer pageCount = domain.getPageCount();
			if (null == pageNum) {
				pageNum = 1;
			}
			if (null == pageSize) {
				pageSize = 10;
			}

			Map map = systemBarService.getPageByBatchNo(pageSize, pageNum, domain);
			List<SystemBarModel> list = (List<SystemBarModel>) map.get("list");
			int recordCount = Integer.valueOf(map.get("count").toString());
			// 页面信息
			if (pageSize * pageNum > recordCount + pageSize - 1) {
				pageNum = 1;
			}
			model.addAttribute("list", list);
			model.addAttribute("pageNum", pageNum);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageCount",
					PmpUtils.getPageCount(recordCount, pageSize));
			model.addAttribute("recordCount", recordCount);
			model.addAttribute("model", domain);
			return "/jsp/map/systemBar/systemBarListAndAdd";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}
	/**
	 * 进入列表页面
	 */
	@RequestMapping("/list")
	public String list(SystemBarDomain domain, Model model,
			HttpServletRequest request) {

		try {// 初始化信息
			MatrixToImageWriter.realPath = request.getSession().getServletContext().getRealPath("/");
			Integer pageNum = domain.getPageNum();
			Integer pageSize = domain.getPageSize();
			Integer pageCount = domain.getPageCount();
			if (null == pageNum) {
				pageNum = 1;
			}
			if (null == pageSize) {
				pageSize = 10;
			}

			Map map = systemBarService.getPageByDomain(pageSize, pageNum, domain);
			List<SystemBarModel> list = (List<SystemBarModel>) map.get("list");
			int recordCount = Integer.valueOf(map.get("count").toString());
			// 页面信息
			if (pageSize * pageNum > recordCount + pageSize - 1) {
				pageNum = 1;
			}
			model.addAttribute("list", list);
			model.addAttribute("pageNum", pageNum);
			model.addAttribute("pageSize", pageSize);
			model.addAttribute("pageCount",
					PmpUtils.getPageCount(recordCount, pageSize));
			model.addAttribute("recordCount", recordCount);
			model.addAttribute("model", domain);
			return "/jsp/map/systemBar/systemBarList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}
    /**  
     * 表单提交日期绑定  
     */  
    @InitBinder  
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    }
    /**
     * 弹出的新增修改页面
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public String edit(SystemBarModel systemBarModel, Model model, HttpServletRequest request) {
    	try{

            String orderId = systemBarModel.getBarId();
    		if(orderId!="add"&&StrUtils.isNotEmpty(orderId)){
    			systemBarModel=systemBarService.getModelByKey(orderId);
    		}
	    	model.addAttribute("model", systemBarModel);
	        return "/jsp/platform/systemBar/systemBarEdit";
	    } catch (Exception e) {
	        log.error("内部异常", e);
	        model.addAttribute("errorMsg", "出错了");
	        return "/jsp/platform/error";
	    }
    }
    /**
     * @return
     */
    @RequestMapping("/update")
    public
    @ResponseBody
    SystemBarModel update(SystemBarModel model) {
        try {
        	systemBarService.update(model);
        	model.setSuccess(true);
        	model.setMsg("保存信息成功");
            log.debug("保存信息成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("保存信息失败");
            log.error("保存信息失败" + e.getMessage(), e);
        }
        return model;
    }

    /**
     * @return
     */
    @RequestMapping("/delete")
    public
    @ResponseBody
    SystemBarModel delete(SystemBarModel model) {
        try {
        	systemBarService.delete(model);
        	model.setSuccess(true);
        	model.setMsg("删除信息成功");
            log.debug("删除信息成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("删除信息失败");
            log.error("删除信息失败" + e.getMessage(), e);
        }
        return model;
    }

    /**
     * @return
     */
    @RequestMapping("/add")
    public
    @ResponseBody
    SystemBarModel add(SystemBarModel model) {
        try {
        	systemBarService.add(model);
        	model.setSuccess(true);
        	model.setMsg("新增信息成功");
            log.debug("新增信息成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("新增信息失败");
            log.error("新增信息失败" + e.getMessage(), e);
        }
        return model;
    }
    /**
     * @return
     */
    @RequestMapping("/addByBatchCount")
    public
    @ResponseBody
    SystemBarModel addByBatchCount(SystemBarModel model, HttpServletResponse response) {
        try {
        	String filePath = systemBarService.addByBatchCount(model);
        	File file = new File(filePath);
        	ReportUtil.download(response, filePath, file.getName());
        	model.setSuccess(true);
        	model.setMsg("生成二维码成功");
            log.debug("生成二维码成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("生成二维码失败");
            log.error("生成二维码失败" + e.getMessage(), e);
        }
        return model;
    }
    /**
     * @return
     */
    @RequestMapping("/downloadByBatchNo")
    public
    @ResponseBody
    SystemBarModel downloadByBatchNo(SystemBarModel model, HttpServletResponse response) {
        try {
        	String batchNo = model.getBatchNo();
        	File file = new File(MatrixToImageWriter.realPath+File.separator+"systemBar/"+batchNo+".zip");
        	ReportUtil.download(response, file.getPath(), file.getName());
        	model.setSuccess(true);
        	model.setMsg("生成二维码成功");
            log.debug("生成二维码成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("生成二维码失败");
            log.error("生成二维码失败" + e.getMessage(), e);
        }
        return model;
    }
    /**
     * @return
     */
    @RequestMapping("/exportByBatchNo")
    public
    @ResponseBody
    SystemBarModel exportByBatchNo(SystemBarModel model, HttpServletResponse response) {
        try {
        	String batchNo = model.getBatchNo();
        	model.setBatchNo(batchNo);
        	List<SystemBarModel> mList = systemBarService.getListByModel(model);
            List<SystemBarDownloadDomain> reportList = new ArrayList<SystemBarDownloadDomain>();
            for (SystemBarModel o : mList) {
                
            	SystemBarDownloadDomain temp = new SystemBarDownloadDomain();
                BeanUtils.copyProperties(o, temp);
                temp.setUrl(PropertyUtil.getValue("mobile_base_url")+"/mobile/offline/index?offLineMerchantCode=&mCode="+o.getmCode()+"&appId=5202991");
                reportList.add(temp);
            }
            Map<Integer, Object> formatAttr = new HashMap<Integer, Object>();
            try {

                String[] header = null;
                header = new String[]{"二维码编号", "二维码链接"};
                String sts = ReportUtil.exportReport(header, reportList, null,
                        "二维码导出", formatAttr, null, response);
                String[] st = sts.split("#");
                ReportUtil.download(response, st[0], st[1]);
            } catch (Exception e) {
                log.error("信用卡查询", e);
            }
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("导出二维码失败");
            log.error("导出二维码失败" + e.getMessage(), e);
        }
        return model;
    }
    @RequestMapping("/downloadByMCode")
    public
    @ResponseBody
    SystemBarModel downloadByMCode(SystemBarModel model, HttpServletResponse response) {
        try {
        	String mCode = model.getmCode();
        	String batchNo = model.getBatchNo();
        	//File file = new File(MatrixToImageWriter.realPath+File.separator+"systemBar/"+batchNo+"/"+DesUtil.encrypt(mCode, "systemBar")+".png");
        	File file = new File(MatrixToImageWriter.realPath+File.separator+"systemBar/"+batchNo+"/"+mCode+".png");
        	ReportUtil.download(response, file.getPath(), file.getName());
        	model.setSuccess(true);
        	model.setMsg("生成二维码成功");
            log.debug("生成二维码成功");
        } catch (Exception e) {
        	model.setSuccess(false);
        	model.setMsg("生成二维码失败");
            log.error("生成二维码失败" + e.getMessage(), e);
        }
        return model;
    }
    /**
     * 弹出的查看二维码
     * @return
     */
    @RequestMapping("/viewBar")
    public String viewBar(SystemBarModel systemBarModel, Model model, HttpServletRequest request) {
    	try{

            String mCode = systemBarModel.getmCode();
            String batchNo = systemBarModel.getBatchNo();
    		//String barPath = "../../systemBar/"+batchNo+"/"+DesUtil.encrypt(mCode, "systemBar")+".png";
            String barPath = "../../systemBar/"+batchNo+"/"+mCode+".png";
    		model.addAttribute("barPath", barPath);
	        return "/jsp/map/systemBar/viewBar";
	    } catch (Exception e) {
	        log.error("内部异常", e);
	        model.addAttribute("errorMsg", "出错了");
	        return "/jsp/platform/error";
	    }
    }
}
